import { getQiniuToken } from '@/services';
import * as qiniu from 'qiniu-js';
import { Toast } from 'vant';

const uploadQiniu = async (file: File, { putExtra, config }: any = {}) => {
  const bucket = import.meta.env.VITE_ENV === 'prod' ? 'ugc-prod' : 'ugc-dev';

  const { token, host } = (await getQiniuToken({ bucket })) || {};

  return new Promise((resolve, reject) => {
    const observer = {
      next(res: any) {
        console.log('上传中', res);
      },
      error(err: any) {
        Toast.fail('文件上传失败，请稍后重试');
        reject(err);
        subscription.unsubscribe();
      },
      complete(res: any) {
        resolve({ ...res, host, key: '/' + res.key });
      },
    };

    const getCurrentTimeStamp = () => new Date();

    const key = `h5/${getCurrentTimeStamp()}/${file.name}`;

    const observable = qiniu.upload(file, key, token, putExtra, config);

    const subscription = observable.subscribe(observer);
  });
};

export default uploadQiniu;
